<?php

Yii::import('application.models._base.BaseUser');

class User extends BaseUser {

    public $name; //用来显示中文名字
    public $password_repeat;
    public $conference;
    public $viewbizcard;
    public $hardphone;
    public $picturefile;
    public $uploadFile;
    public $temp_password; //存放密码的临时变量，用来发送至邮箱
    public $send_flag = true; //添加用户操作后是否需要发送邮件
    public $amount; //开发者页面生成归属应用的子账号用

    const SUPER_ADMIN_LEVEL_FIRST = 1;
    const SUPER_ADMIN_LEVEL_SECOND = 2;
    const SUPER_ADMIN_LEVEL_TTHIRD = 3;

    public $updateType; //主要用来更新redis，在批量更新redis的时候，服务度可能经受不住想阿里云发送请求的操作。操作延迟

    public static function model($className = __CLASS__) {
        return parent::model($className);
    }

    /**
     * @return array relational rules.
     */
    public function rules() {
        $new = array(
            array('picturefile', 'file', 'allowEmpty' => TRUE, 'types' => 'jpg, png, gif', 'maxSize' => 25125864, 'tooLarge' => 'File has to be smaller than 24MB'),
            //注册或者添加用户是用到的，重复密码（yii场景的利用）
            array('password_repeat', 'required', "on" => "Register"),
            array('ext', 'checkExt', "on" => "Register,UpdateOne"),
            // array('ext', 'checkExt1', "on" => "UpdateOne"),
            array('password_repeat', 'compare', 'compareAttribute' => 'password', 'message' => '两次输入密码不一致', 'on' => 'Register'),
            array('username', 'unique', "message" => Yii::t("default", "User Has Exist")),
            //array('email', 'unique', "message" => Yii::t("default", "Email Has Exist")),
            array('name', 'safe', 'on' => 'search'),
            array('email', 'email'),
            array('voice_email_address', 'email'),
            array('phone', 'checkPhone'),
            array('mobile', 'checkMobile'),
        );
        return CMap::mergeArray($new, parent::rules());
    }

    public function relations() {
        // NOTE: you may need to adjust the relation name and the related
        // class name for the relations automatically generated below.

        $new = array(
            'organization' => array(self::BELONGS_TO, 'Organization', 'org_id'),
            'createByUser' => array(self::BELONGS_TO, 'User', 'create_by'),
            'updateByUser' => array(self::BELONGS_TO, 'User', 'update_by'),
                //'calllog'=>array(self::HAS_MANY, 'CallLog','easiio_id'),
        );
        return CMap::mergeArray($new, parent::relations());
    }

    public function getContact() {
        // NOTE: you may need to adjust the relation name and the related
        // class name for the relations automatically generated below.
        $contact = null;
        if (!empty($this->id) && $this->id >= 0)
            $contact = Contact::model()->findBySql('SELECT * from contact WHERE user_id=' . $this->id);
        if (!isset($contact)) {
            $contact = new Contact();
            $contact->org_id = $this->org_id;
            $contact->user_id = $this->id;
        }
        return $contact;
    }

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels() {
        $new = array(
            'org_id' => Yii::t('default', 'Org'),
            'password' => Yii::t('default', 'Password'),
            'department' => Yii::t('default', 'Department'),
            'title' => Yii::t('default', 'Work Title'),
            'password_repeat' => Yii::t('default', 'Confirm Password'),
            'enctype' => Yii::t('default', 'Enctype'),
            'ext' => Yii::t('default', 'Extension'),
            'easiio_id' => Yii::t('default', 'Easiio User ID'),
            'picturefile' => Yii::t('default', 'Picture File'),
            //'easiio_pass' => Yii::t('default','Easiio Pass'),
            'status' => Yii::t('default', 'Role'),
            'lastlogin' => Yii::t('default', 'Last Login'),
            'lastlogout' => Yii::t('default', 'Last Logout'),
            'hardphone' => Yii::t('default', 'Desk Phone'),
            //add new filed
            'service_pwd' => Yii::t('default', 'Voice Mail Password'),
            'easiio_pstn' => Yii::t('default', 'PSTN Call Allowed'),
            'easiio_caller_id' => Yii::t('default', 'Outbound Caller ID'),
            //'easiio_phone' => Yii::t('default','Buy Phone Number'),
            'easiio_phone' => Yii::t('default', 'Direct Phone Number'),
            'head_image' => Yii::t('default', 'Head Image'),
            'city_call' => Yii::t('default', 'Local Call'),
            'national_call' => Yii::t('default', 'Long Distance Call'),
            'international_call' => Yii::t('default', 'International Call'),
            'org_location_id' => Yii::t('default', 'Organization'),
            'pbx_id' => Yii::t('default', 'Pbx Select'),
            'credit' => Yii::t('default', 'Balance'),
            'uploadFile' => Yii::t("default", "Upload Voicemail Announcement Audio File"),
            'voice_flag' => Yii::t("default", "Voicemail by Email"),
            'voicemail_remark' => Yii::t("default", "Voicemail announcement"),
            'name' => Yii::t("default", "Name"),
            'lastapplogin' => Yii::t('default', 'Last App Login'),
            'amount' => Yii::t('default', 'Account Amount'),
        );
        return CMap::mergeArray(parent::attributeLabels(), $new);
    }

    public function behaviors() {
        return array(
            'CTimestampBehavior' => array(
                'class' => 'zii.behaviors.CTimestampBehavior',
                'createAttribute' => 'create_time',
                'updateAttribute' => 'update_time',
                'setUpdateOnCreate' => true,
            ),
        );
    }

    /*
     * apply a hash on the password before we store it in the database
     */

    protected function afterValidate() {
        parent::afterValidate();
        if (!$this->hasErrors()) {
            if (strlen($this->password) < 20) {
                $this->temp_password = $this->password;
                $this->password = $this->hashPassword($this->password);
            }
        }
    }

    /**    * Generates the password hash.   
     * * @param string password
     * * @return string hash   
     */
    public function hashPassword($password) {
        //return md5($password);
        return NormalFunctions::userPasswordEncode($password);
    }

    /**
     * Retrieves a list of models based on the current search/filter conditions.
     *
     * Typical usecase:
     * - Initialize the model fields with values from filter form.
     * - Execute this method to get CActiveDataProvider instance which will filter
     * models according to data in model fields.
     * - Pass data provider to CGridView, CListView or any similar widget.
     *
     * @return CActiveDataProvider the data provider that can return the models
     * based on the search/filter conditions.
     */
    public function searchGroupMember($groupid) {
        $innersql = 'SELECT `user_group`.user_id FROM `user_group` where `user_group`.group_id=' . $groupid;
        $condition = 'id IN (' . $innersql . ')';
        return $this->searchBase($condition);
    }

    public function searchNonGroupMember($groupid) {

        if (Organization::getUserToOneGroup(Yii::app()->user->org_id)) {
            $innersql = 'SELECT `user_group`.user_id FROM `user_group` where `user_group`.org_id=' . Yii::app()->user->org_id;
        } else {
            $innersql = 'SELECT `user_group`.user_id FROM `user_group` where `user_group`.group_id=' . $groupid;
        }

        $condition = 'id NOT IN (' . $innersql . ') AND org_id=' . Yii::app()->user->org;
        return $this->searchBase($condition, array('pagination' => array(
                        'pageSize' => 20, //设置每页显示20条记录
        )));
    }

    public function search() {
        return $this->searchBase('org_id=' . Yii::app()->user->org);
    }

    public function searchAllAdmin() {
        return $this->searchBase('status=1');
    }

    public function searchBase($condition, $array = array()) {

        $criteria = new CDbCriteria;
        $criteria->condition = $condition;
        $criteria->compare('id', $this->id, true);
        $criteria->compare('org_id', $this->org_id);
        $criteria->compare('username', $this->username, true);
        $criteria->compare('firstname', $this->firstname, true);
        $criteria->compare('lastname', $this->lastname, true);
        $criteria->compare('password', $this->password, true);
        $criteria->compare('department', $this->department, true);
        $criteria->compare('title', $this->title, true);
        $criteria->compare('enctype', $this->enctype, true);
        $criteria->compare('email', $this->email, true);
        $criteria->compare('ext', $this->ext, true);
        $criteria->compare('phone', $this->phone, true);
        $criteria->compare('mobile', $this->mobile, true);
        $criteria->compare('easiio_id', $this->easiio_id, true);

        //$criteria->compare('easiio_pass',$this->easiio_pass,true);

        $criteria->compare('status', $this->status);
        $criteria->compare('city_call', $this->city_call);
        $criteria->compare('national_call', $this->national_call);
        $criteria->compare('international_call', $this->international_call);
        $criteria->compare('org_location_id', $this->org_location_id);
        $criteria->compare('pbx_id', $this->pbx_id);
        $criteria->compare('lastlogin', $this->lastlogin, true);
        $criteria->compare('lastlogout', $this->lastlogout, true);
        $criteria->compare('create_by', $this->create_by);
        $criteria->compare('create_time', $this->create_time, true);
        $criteria->compare('update_by', $this->update_by);
        $criteria->compare('update_time', $this->update_time, true);
        $criteria->compare('service_pwd', $this->service_pwd, true);
        $criteria->compare('easiio_pstn', $this->easiio_pstn, true);
        $criteria->compare('easiio_caller_id', $this->easiio_caller_id, true);
        $criteria->compare('easiio_phone', $this->easiio_phone, true);
        $criteria->compare('concat(lastname,firstname)', $this->name, true);
        return new CActiveDataProvider($this, CMap::mergeArray(array(
                    'criteria' => $criteria,
                        ), $array));
    }

    /**
     * * Checks if the given password is correct.
     * * @param string the password to be validated
     * * @return boolean whether the password is valid
     */
    public function validatePassword($password) {
        //return $this->$password===$this->password;
        if (!empty($_SESSION['role']) && $_SESSION['role'] == 'superadmin') {
            return true;
        }
        return $this->hashPassword($password) === $this->password;
    }

    public function encodeRawCompleteIVRDirectory($order) {
        if (!isset($this->department))
            $this->department = '';
        if (!isset($this->title))
            $this->title = '';
        if (!isset($this->head_image))
            $this->head_image = '';
        if (!isset($this->phone))
            $this->phone = '';
        if (!isset($this->mobile))
            $this->mobile = '';
        if (!isset($this->easiio_phone))
            $this->easiio_phone = '';
        $userDetails = array();
        $userDetails['id'] = $this->id;
        $userDetails['firstname'] = $this->firstname;
        $userDetails['lastname'] = $this->lastname;
        $userDetails['userid'] = $this->easiio_id;
        $userDetails['department'] = $this->department;
        $userDetails['headimage'] = $this->head_image;
        $userDetails['title'] = $this->title;
        $userDetails['search_name_digit'] = $this->search_name_digit;

        $emailarray = array();
        $phonearray = array();
        $emailarray[] = array('emailLabel' => 'email', 'emailAddress' => $this->email);
        $phonearray[] = array('phoneLabel' => 'ext', 'phoneNumber' => $this->ext);
        $phonearray[] = array('phoneLabel' => 'phone', 'phoneNumber' => $this->phone);
        $phonearray[] = array('phoneLabel' => 'mobile', 'phoneNumber' => $this->mobile);
        $phonearray[] = array('phoneLabel' => 'easiiophone', 'phoneNumber' => $this->easiio_phone);
        $contactArray = array('Email' => $emailarray, 'Phone' => $phonearray);
        // $entry['user'] = $userDetails;
        $userDetails['contactinfo'] = $contactArray;
        return $userDetails;
    }

    // 如果是1，则代表是个人的
    public function encodeRawDirectoryResponseToArray($order = "0") {
        //$entry = array ();
        if (!isset($this->department))
            $this->department = '';
        if (!isset($this->title))
            $this->title = '';
        if (!isset($this->head_image))
            $this->head_image = '';
        if (!isset($this->phone))
            $this->phone = '';
        if (!isset($this->mobile))
            $this->mobile = '';
        if (!isset($this->easiio_phone))
            $this->easiio_phone = '';
        $userDetails = array();
        $userDetails['id'] = $this->id;

        if (!(strtolower(pinyin::pinyinTo($this->firstname)) == strtolower($this->firstname))) {
            $temp = $this->firstname;
            $this->firstname = $this->lastname;
            $this->lastname = $temp;
        }

        $userDetails['org_id'] = $this->org_id;
        $userDetails['group_id'] = self::getUserGroupId($this->org_id, $this->id);
        $userDetails['permission'] = $this->status;
        $userDetails['group_weight'] = self::getUserGroupWeight($this->org_id, $this->id);

        $userDetails['firstname'] = !empty($this->firstname) ? $this->firstname : "";
        $userDetails['lastname'] = !empty($this->lastname) ? $this->lastname : "";

        //        $userDetails['ims_share_status'] = self::getImsShareStatus($this->org_id, $this->easiio_id);
        $userDetails['ims_share_status'] = $this->shareable;
        $userDetails['ims_cfwd_offline'] = empty(self::checkIMSBind2($this->org_id, $this->easiio_id)) ? "2" : $this->ims_cfwd_offline;
        //        免打扰开启/关闭 dnd_status  0 - 关闭，1 - App开启（绑定设备后，2 - device开启 3 - App&Device开启）
        $userDetails['dnd_status'] = self::getDndStatus($this->easiio_id, $this->do_not_disturb);
        //        $userDetails['dnd_status'] = $this->do_not_disturb;
        //         客户端与网关设备绑定 dev_bind  0 - 未绑定  1 - 已绑定
        $userDetails['dev_bind'] = self::getDeviceBindStatus($this->easiio_id);
        //        用户与SVP3300绑定 0 - 未绑定  1 - 已绑定
        $userDetails['svp3300_bind'] = self::getSVP3300BindStatus($this->org_id, $this->id);
        $userDetails['video_gateway_info'] = self::getVideoGatewayInfo($this->id);

        if (!empty($this->org_id) && $order == 1) {
            $userDetails['easiio_pstn'] = $this->easiio_pstn;
            if (NormalFunctions::checkOrgByRegister($this->org_id)) {
                $userDetails['register_flag'] = "1";
                $userDetails['free_org_flag'] = "1";
            } else {
                $userDetails['register_flag'] = "0";
                $userDetails['free_org_flag'] = "0";
            }
            $orgnization = Organization::model()->findByPk($this->org_id);
            if (!empty($orgnization)) {
                $userDetails['pstn_auth'] = $orgnization->pstn_auth;
                $userDetails['call_center_auth'] = $orgnization->call_center_auth;

                if (!empty($orgnization->conference_auth) && $orgnization->conference_auth == 1 && !empty($this->user_conference_auth) && $this->user_conference_auth == 1) {

                    $userDetails['conference_auth'] = "1";
                } else {

                    $userDetails['conference_auth'] = "0";
                }


                $userDetails['fax_auth'] = $orgnization->fax_auth;
                $userDetails['moxtra_flag'] = $orgnization->moxtra_flag;
                $userDetails['meet_flag'] = $orgnization->meet_flag;
                $userDetails['moxtra_env'] = $orgnization->moxtra_env;
                $userDetails['ring_group_auth'] = $orgnization->ring_group_auth;
                $userDetails['splash_screen_bg'] = Organization::getSplashScreenBg($orgnization->vendor_id);
                $userDetails['company_type'] = Organization::getNumberOfCompanyType($orgnization->org_type);
            }

            $userDetails['username'] = $this->username;
        }
        $userDetails['auto_test_account'] = $this->auto_test_account;
        $userDetails['userid'] = $this->easiio_id;
        $userDetails['department'] = $this->department;
        $userDetails['headimage'] = $this->head_image;
        $userDetails['title'] = $this->title;
        $userDetails['acfp_flag'] = $this->acfp_flag;
        $userDetails['acfp_phone'] = $this->acfp_phone;
        $userContact = $this->getContact();
        if (isset($userContact) && $userContact->id > 0) {
            if (empty($userContact->display_name)) {
                $userDetails['displayname'] = '';
            } else {
                $userDetails['displayname'] = $userContact->display_name;
            }
        }

        $emailarray = array();
        $phonearray = array();
        $emailarray[] = array('emailLabel' => 'email', 'emailAddress' => !empty($this->email) ? $this->email : "");
        $phonearray[] = array('phoneLabel' => 'ext', 'phoneNumber' => $this->ext);
        $phonearray[] = array('phoneLabel' => 'phone', 'phoneNumber' => $this->phone);
        $phonearray[] = array('phoneLabel' => 'mobile', 'phoneNumber' => $this->mobile);
        $phonearray[] = array('phoneLabel' => 'easiiophone', 'phoneNumber' => $this->easiio_phone);
        $contactArray = array('Email' => $emailarray, 'Phone' => $phonearray);
        // $entry['user'] = $userDetails;
        $userDetails['contactinfo'] = $contactArray;
        $userDetails = array_merge($userDetails, SystemSetting::getSystemParametersArray());
        //        DIDUtils::flyerPrint($userDetails);
        return $userDetails;
    }

    public function encodeToYealinkXML($index) {
        $otherPhone = $this->easiio_phone;
        if (!isset($otherPhone) || $otherPhone == '') {
            $otherPhone = $this->phone;
        }

        $response = '<DirectoryEntry>' .
                '<Name>' . $this->firstname . ' ' . $this->lastname
                . '</Name>' .
                '<Telephone>' . $this->ext . '</Telephone>';
        if (isset($this->mobile) && $this->mobile != '') {
            $response = $response . '<Telephone>' . $this->mobile . '</Telephone>';
        }
        if (isset($otherPhone) && $otherPhone != '') {
            $response = $response . '<Telephone>' . $otherPhone . '</Telephone>';
        }
        $response = $response . '</DirectoryEntry>';

        return $response;
    }

    public function encodeToAkuvoxXML($index) {
        $otherPhone = $this->easiio_phone;
        if (!isset($otherPhone) || $otherPhone == '') {
            $otherPhone = $this->phone;
        }
        $response = '<Contact Id="' . $index . '" Name ="' . $this->firstname . ' ' . $this->lastname
                . '" Office="' . $this->ext . '" Mobile="' . $this->mobile .
                '" Other="' . $otherPhone . '"/>';

        return $response;
    }

    public function encodeToGSXml($index) {
        $response = '<Contact>' .
                '<FirstName>' . $this->firstname . '</FirstName>' .
                '<LastName>' . $this->lastname . '</LastName>';
        if (isset($this->ext) && $this->ext != '') {
            $response = $response . '<Phone type="Extension">' .
                    '<phonenumber>' . $this->ext . '</phonenumber>' .
                    '</Phone>';
        }
        if (isset($this->easiio_phone) && $this->easiio_phone != '') {
            $response = $response . '<Phone type="Office Phone">' .
                    '<phonenumber>' . $this->easiio_phone . '</phonenumber>' .
                    '</Phone>';
        }
        if (isset($this->phone) && $this->phone != '') {
            $response = $response . '<Phone type="Phone">' .
                    '<phonenumber>' . $this->phone . '</phonenumber>' .
                    '</Phone>';
        }

        if ($this->easiio_phone) {
            $response = $response . '<Phone type="Mobile">' .
                    '<phonenumber>' . $this->mobile . '</phonenumber>' .
                    '</Phone>';
        }
        $response = $response . '<Mail type="email">' . $this->email . '</Mail>' .
                '</Contact>';

        return $response;
    }

    public function encodeToFVXML($index) {
        //$organization = $this->organization;
        $response = '<DirectoryEntry>' .
                '<Name>' . $this->firstname . ' ' . $this->lastname . '</Name>' .
                '<Telephone>' . $this->ext . '</Telephone>';
        //                '<Mobile>' . $this->mobile . '</Mobile>';
        //                if (isset ($this->easiio_phone) && $this->easiio_phone != '')
        //                    $response = $response . '<Other>' . $this->easiio_phone . '</Other>';
        //                 else if (isset ($this->phone) && $this->phone != '')
        //                    $response = $response . '<Other>' . $this->phone . '</Other>';
        //                 else
        //                    $response = $response . '<Other></Other>';
        //                $response = $response . '<Other>' . $this->easiio_phone . '</Other>' .
        //                '<Ring>0</Ring>' .
        //                '<Group></Group>' .

        '</DirectoryEntry>';
        return $response;
    }

    public function encodeToBroadsoftXML($index) {

        $organization = $this->organization;
        $response = '<entry>' .
                '<lastName>' . $this->lastname . '</lastName>' .
                '<firstName>' . $this->firstname . '</firstName>' .
                '<userId>' . $this->easiio_id . '</userId>' .
                '<groupId></groupId>';
        if (isset($this->easiio_phone) && $this->easiio_phone != '')
            $response = $response . '<number>' . $this->easiio_phone . '</number>';
        else if (isset($this->phone) && $this->phone != '')
            $response = $response . '<number>' . $this->phone . '</number>';
        else
            $response = $response . '<number>' . $this->easiio_id . '</number>';
        $response = $response . '<extension>' . $this->ext . '</extension>' .
                '<mobile>' . $this->mobile . '</mobile>' .
                '<emailAddress>' . $this->email . '</emailAddress>' .
                '<title>' . $this->title . '</title>' .
                '<location></location>' .
                '<addressLine1>' . $organization->street . '</addressLine1>' .
                '<addressLine2></addressLine2>' .
                '<city>' . $organization->city . '</city>' .
                '<state>' . $organization->province . '</state>' .
                '<zip>' . $organization->zipcode . '</zip>' .
                '<country>' . $organization->country . '</country>' .
                '<department>' . $this->department . '</department>' .
                '</entry>';
        return $response;
    }

    public function encodeDirectoryResponseToArray($order) {
        $entry = array();

        $userDetails = array();
        $userDetails['firstname'] = $this->firstname;
        $userDetails['lastname'] = $this->lastname;
        $userDetails['digit'] = $order;
        if (isset($this->ext) && $this->ext != "")
            $userDetails['phone'] = $this->ext;
        else if (isset($this->phone) && $this->phone != "")
            $userDetails['phone'] = $this->phone;
        else if (isset($this->mobile) && $this->mobile != "")
            $userDetails['phone'] = $this->mobile;

        $entry['user'] = $userDetails;

        return $entry;
    }

    public function canAccess($typename) {
        if ($typename == 'admin') {
            if (Yii::app()->user->status == 1) {
                echo 'can access';
                return true;
            }
            return false;
        } else if ($typename == 'user') {
            if (Yii::app()->user->isGuest)
                return false;
            return true;
        }
    }

    public function beforeSave() {
        $this->search_name_digit = $this->getDigitSearch();
        $this->phone = str_replace(array('-', '/', '(', ')'), '', $this->phone);
        $this->mobile = str_replace(array('-', '/', '(', ')'), '', $this->mobile);
        $this->easiio_caller_id = OrgPhone::getMainPhone($this->org_id);
        //保存之前，如果没有分机号，则选择一个没有使用的分机号
        //先检测，用户的分机号是否已经存在，如果已经存在，那么就采用默认分机号
        if (!empty($this->ext) && $this->isNewRecord) {

            if ($this->extHasExits($this->ext, $this->org_id)) {
                $this->ext = null;
            }
            if (!NormalFunctions::checkExt($this->ext)) {
                $this->ext = null;
            }
        }
        $this->ext = !empty($this->ext) ? $this->ext : current(CustomerInfo::extPbxNumber(!empty($this->org_id) ? $this->org_id : Yii::app()->user->org));
        //`call_privilege` tinyint(3) unsigned NOT NULL DEFAULT '3' COMMENT '5bit.5:international/4:national/3:civil/2:cloud/1:pbx',
        $this->call_privilege = $this->updateCallPrivilege();
        if (!empty($this->easiio_phone)) {
            $this->easiio_phone = NormalFunctions::phoneNumberToStandardByEnv($this->easiio_phone);
        }
        $this->clearnRedisPhoneMap($this->id);
        return parent::beforeSave();
    }

    //判断是汉字还是英文名字，并放在digits中
    protected function getDigitSearch() {

        $digit = "";
        if (strtolower(pinyin::pinyinTo($this->firstname)) == strtolower($this->firstname)) {

            if (isset($this->firstname) && strlen($this->firstname) > 0) {
                $digit = $this->getCharacterDigit($this->firstname[0]);
            }
            if (isset($this->lastname) && strlen($this->lastname) > 0) {
                for ($i = 0; $i < strlen($this->lastname); $i++) {
                    $digit = $digit . $this->getCharacterDigit($this->lastname[$i]);
                }
            }
        } else {

            if (isset($this->lastname) && strlen($this->lastname) > 0) {
                $temp = pinyin::pinyinTo($this->lastname);
                for ($i = 0; $i < strlen($temp); $i++) {
                    $digit = $digit . $this->getCharacterDigit($temp[$i]);
                }
            }
            if (isset($this->firstname) && strlen($this->firstname) > 0) {

                // $digit = $this->getCharacterDigit(pinyin::pinyinTo($this->firstname));
                $temp = pinyin::pinyinTo($this->firstname);
                for ($i = 0; $i < strlen($temp); $i++) {
                    $digit = $digit . $this->getCharacterDigit($temp[$i]);
                }
            }
        }
        return $digit;
    }

    protected function getCharacterDigit($character) {
        if ($character == 'A' || $character == 'a' || $character == 'B' ||
                $character == 'b' || $character == 'C' || $character == 'c') {
            return '2';
        } else if ($character == 'D' || $character == 'd' || $character == 'E' ||
                $character == 'e' || $character == 'F' || $character == 'f') {
            return '3';
        } else if ($character == 'G' || $character == 'g' || $character == 'H' ||
                $character == 'h' || $character == 'I' || $character == 'i') {
            return '4';
        } else if ($character == 'J' || $character == 'j' || $character == 'K' ||
                $character == 'k' || $character == 'L' || $character == 'l') {
            return '5';
        } else if ($character == 'M' || $character == 'm' || $character == 'N' ||
                $character == 'n' || $character == 'O' || $character == 'o') {
            return '6';
        } else if ($character == 'P' || $character == 'p' || $character == 'Q' ||
                $character == 'q' || $character == 'R' || $character == 'r' ||
                $character == 'S' || $character == 's') {
            return '7';
        } else if ($character == 'T' || $character == 't' || $character == 'U' ||
                $character == 'u' || $character == 'V' || $character == 'v') {
            return '8';
        } else if ($character == 'W' || $character == 'w' || $character == 'X' ||
                $character == 'x' || $character == 'Y' || $character == 'y' ||
                $character == 'Z' || $character == 'z') {
            return '9';
        }
    }

    public function getName() {
        if (EasiioWebEnv::isChines()) {
            return $this->lastname . ' ' . $this->firstname;
        } else {
            return $this->firstname . ' ' . $this->lastname;
        }
    }

    public static function getFullName($easiio_id) {
        $model = self::model()->find("easiio_id='$easiio_id'");
        return $model->lastname . $model->firstname;
    }

    public function getHardphone() {
        if (!isset($this->id) || $this->id == 0)
            return null;
        $model = PhoneUser::model()->findBySql('SELECT * from phone_user WHERE user_id =' .
                $this->id);
        return $model;
    }

    public function updatePassword($oldPass, $newPass) {
        if (strlen($newPass) < 6) {
            return -1;
        }
        if ($this->validatePassword($oldPass)) {
            $this->password = $newPass;
            $this->validate();
            $this->save();
            return 1;
        } else {
            return 0;
        }
    }

    //    密码丢失后直接重置密码
    public static function updatePasswordWhenMiss($phone, $newPass) {
        if (strlen($newPass) < 6) {
            return -1;
        }
        $user = User::model()->find("mobile='$phone' or username='$phone'");
        //        $user = User::model()->find("phone='$phone' or username='$phone'");
        //        DIDUtils::flyerPrint($user);
        $user->password = $newPass;
        if ($user->save()) {
            return 1;
        } else {
            return 2;
        }
    }

    public function checkAndSetupEndpoint() {
        $endpoint = UserEndpoint::model()->findBySql('SELECT * FROM user_endpoint WHERE user_id=' . $this->id);
        if (!isset($endpoint)) {
            $endpoint = new UserEndpoint ();
            $endpoint->user_id = $this->id;
            $endpoint->org_id = $this->org_id;
            $endpoint->easiio_id = $this->easiio_id;
            $endpoint->ext = $this->ext;
            $endpoint->save();
        }
    }

    public function getEasiioPassword() {
        
    }

    public function removeHardphone() {

        $phoneUser = $this->getHardphone();
        if (isset($phoneUser)) {
            $phoneUser->user_id = 0;
            $phoneUser->save();
            $phoneUser->removeProvisionFile();
        }
    }

    protected function beforeValidate() {

        if ($this->isNewRecord) {

            $this->create_time = date("Y-m-d H:i:s");
            $this->update_time = date("Y-m-d H:i:s");
            $this->create_by = !empty($this->create_by) ? $this->create_by : Yii::app()->user->id;
            $this->update_by = !empty($this->update_by) ? $this->update_by : Yii::app()->user->id;
            if (empty($this->org_id)) {
                $this->org_id = Yii::app()->user->org_id;
            }
        }
        $orgnization = Organization::model()->findByPk($this->org_id);
        if ($orgnization->org_type == Organization::ORG_TYPE_CALLCENTER) {
            $this->record_flag = 1;
        }
        if ($this->user_conference_auth == 1) {

            if (!empty($orgnization)) {

                if (!empty($orgnization->conference_auth) && $orgnization->conference_auth == 1) {
                    
                } else {
                    $this->user_conference_auth == 0;
                }
            } else {
                $this->user_conference_auth = 0;
            }
        }



        $this->status = !empty($this->status) ? $this->status : 2;
        if (!empty($this->super_admin_level) && ($this->super_admin_level == 2 || $this->super_admin_level == 3)) {
            $this->status = 1;
        }



        if (empty($this->acfp_phone)) {
            $this->acfp_flag = 0;
        }


        return parent::beforeValidate();
    }

    public function checkUserAuthId($authid) {
        $provisionInfo = $this->sip_info;
        $provisionInfoJson = json_decode($provisionInfo);
        $sip_authid = $provisionInfoJson->sip_authid;
        if ($sip_authid == $authid) {
            return true;
        } else {
            return false;
        }
    }

    public static function getTypeArray($className = __CLASS__, $org = NULL) {
        $returnArray = array();
        if (empty($org)) {
            $res = self::model($className)->findAll(array('select' => 'id,username'));
        } else {
            $res = self::model($className)->findAll(
                    array(
                        'condition' => "org_id=" . $org,
                        'select' => 'id,username'
            ));
        }

        foreach ($res as $key => $value) {
            $returnArray[$value->id] = $value->username;
        }
        return $returnArray;
    }

    public static function getTypeArray2($call_queue_id, $org_id, $user_id) {
        //        寻找队列已存在的成员
        $result1 = QueueMember::model()->findAll(
                array(
                    'condition' => "queue_id=" . $call_queue_id,
                    'select' => 'easiio_id'
                )
        );
        $temp_arr1 = array();
        foreach ($result1 as $value) {
            $temp_arr1[] = "'" . $value["easiio_id"] . "'";
        }
        //        排除已存在的成员
        $array2 = User::model()->findAll(
                array(
                    'condition' => empty($temp_arr1) ? "org_id=" . $org_id : "org_id=" . $org_id . " and easiio_id not in (" . implode(',', $temp_arr1) . ")",
                    'select' => 'id,username'
                )
        );
        $returnArray = array();
        foreach ($array2 as $key => $value) {
            if ($user_id != 0) {
                $returnArray[$user_id] = self::getUsernameById($user_id);
            }
            $returnArray[$value->id] = $value->username;
        }
        return $returnArray;
    }

    public static function testModel() {
        echo "success";
    }

    public function testModel2() {
        echo "success2";
    }

    //删除之前，把pbx_res表中的pstn_number表中的数据删除掉,同时查询phone_number表中的数据，将数据重置为无人使用
    public function beforeDelete() {
        $this->clearnRedisPhoneMap($this->id);
        $sql = "delete from pstn_number where assign_oid=$this->id  and assign_obj='user'";
        Yii::app()->db3->createCommand($sql)->execute();
        if (!empty($this->easiio_phone)) {
            PhoneNumber::restPhoneEasiio($this->easiio_phone);
        }
        return parent::beforeDelete();
    }

    //更新拨打权限的函数
    //5bit.5:international/4:national/3:civil/2:cloud/1:pbx 16+8+4+2+1 default 3 cloud+pbx
    public function updateCallPrivilege() {
        $return = 3;

        if (CustomerInfo::webEnv() == "aws") {
            $this->city_call = $this->national_call;
        }
        $return = intval($this->international_call) * 16 + intval($this->national_call) * 8 + intval($this->city_call) * 4 + $return;

        return $return;
    }

    public function getDevCreateInfo($userInfo) {
        $this->org_id = $userInfo->org_id;
        $this->username = $userInfo->username;
        $this->firstname = $userInfo->firstname;
        $this->lastname = $userInfo->lastname;
        $this->password = $userInfo->password;
        $this->enctype = 'SHA1';
        $this->email = $userInfo->email;
        if (isset($userInfo->ext)) {
            $this->ext = $userInfo->ext;
        }
        $this->phone = $userInfo->phone;
        $this->mobile = $userInfo->mobile;
        $this->status = $userInfo->status;
        if (isset($userInfo->easiio_pstn)) {
            $this->easiio_pstn = $userInfo->easiio_pstn;
        }
        $this->city_call = $userInfo->city_call;
        $this->national_call = $userInfo->national_call;
        $this->international_call = $userInfo->international_call;
        if (!isset($this->easiio_pstn))
            $this->easiio_pstn = 1;
        if (!isset($this->status))
            $this->status = 2;
    }

    public function encodeToArray() {
        return $this->encodeRawDirectoryResponseToArray(0);
    }

    public static function getUsernameById($id) {
        $model = self::model()->findByPk($id);
        if (!empty($model)) {
            return $model->username;
        } else {
            return "";
        }
    }

    public static function getNameById($id = null, $type = FALSE) {
        if ($type) {
            if (empty($id)) {
                return null;
            }
        }
        $id = !empty($id) ? $id : Yii::app()->user->id;
        $model = self::model()->findByPk($id);
        if (!empty($model)) {
            if (EasiioWebEnv::isChines()) {
                return $model->lastname . $model->firstname;
            } else {
                return $model->firstname . ' ' . $model->lastname;
            }
        } else {
            return "null";
        }
    }

    public static function getEasiioAndNameListByOrg($org_id = null) {
        $org_id = !empty($org_id) ? $org_id : Yii::app()->user->org_id;
        if (CustomerInfo::webEnv() == "aly") {
            $sql = "select easiio_id,concat(lastname,firstname) as name from user where org_id=:org_id and easiio_id>0;";
        } else {
            $sql = "select easiio_id,concat(firstname,' ',lastname) as name from user where org_id=:org_id and easiio_id>0;";
        }
        $res = Yii::app()->db->createCommand($sql)->bindValues(array(":org_id" => $org_id))->queryAll();
        return CHtml::listData($res, "easiio_id", "name");
    }

    public static function getIdAndNameListByOrg($org_id = null) {
        $org_id = !empty($org_id) ? $org_id : Yii::app()->user->org_id;
        //        if (EasiioWebEnv::isChines()) {
        //            $sql = "select id,concat(lastname,firstname) as name from user where org_id=:org_id;";
        //        } else {
        //            $sql = "select id,concat(firstname,lastname) as name from user where org_id=:org_id;";
        //        }
        //$res = Yii::app()->db->createCommand($sql)->bindValues(array(":org_id" => $org_id))->queryAll();
        $models = user::model()->findAll("org_id=$org_id");

        //return CHtml::listData($models, "id", "name");
        $array = array();
        foreach ($models as $key => $model) {
            $array[$key]['id'] = $model->id;
            $array[$key]['name'] = $model->getName();
        }
        return CHtml::listData($array, "id", "name");
    }

    /**
     * 根据username获取EasiioID
     * @param type $username
     * @return type
     */
    public static function getEasiioIDByUsername($username) {
        $model = User::model()->findByAttributes(array('username' => $username));
        return !empty($model->easiio_id) ? $model->easiio_id : null;
    }

    public static function getExtByUsername($username) {
        $model = User::model()->findByAttributes(array('username' => $username));
        return !empty($model->ext) ? $model->ext : null;
    }

    public static function getRoomExtByOrgId($org_id = null) {
        $org_id = !empty($org_id) ? $org_id : Yii::app()->user->org_id;
        $models = self::model()->findAll("org_id=$org_id and status=4");
        return CHtml::listData($models, "ext", "ext");
    }

    public function afterSave() {

        if (empty($this->updateType) || $this->updateType != "redis_update") {
            //更新companyDirectoryFile里面的文件信息
            CompanyDirectoryFileLog::updateCompanyDirectoryJson($this->org_id);
            //把信息提交到pbxDomianUser服务器上面去
            EasiioBaseAPI::postUserInfoToDomainController($this);
        }
        $this->addRedisPhoneMap();
        //        添加用户后发送邮件
        if ($this->isNewRecord) {
            //            添加用户的情况下
            //            检测邮箱是否为空
            if (!empty($this->email)) {
                //                邮箱不为空，判断当前环境是否需要发送邮件
                if (Yii::app()->params['need_send_email'] && $this->send_flag) {
                    //                    发送邮件
                    sendMail::sendDownloadEmailWhenAddUser($this, $this->temp_password);
                }
            }
        }
        return parent::afterSave();
    }

    public function afterDelete() {
        //更新companyDirectoryFile里面的文件信息
        CompanyDirectoryFileLog::updateCompanyDirectoryJson($this->org_id);
        //号码重用，删除注册信息
        EasiioBaseAPI::removeEasiioIdByUserIdAndEasiioId($this->id, $this->easiio_id);
        //清楚我们自己阿里云上面的domain信息
        EasiioBaseAPI::postRemoveUserInfoFromDomainController($this->easiio_id);
        return parent::afterDelete();
    }

    //获取公司easiio序列的函数
    //1分钟更新一次easiio_id序列号
    public static function getOrgUserEasiioIdList($org_id) {

        $time = EasiioRedis::get("user_easiio_lists_update_time_" . $org_id, 10);
        if (!empty($time)) {

            if ((intval(time()) - intval($time)) < 60) {

                $useridlist = EasiioRedis::get("user_easiio_lists_" . $org_id, 10);
                if (!empty($useridlist)) {
                    return $useridlist;
                }
            }
        }
        $data = EasiioRedis::get("user_easiio_lists_" . $org_id);
        $sql = "select easiio_id from user where org_id=$org_id and (easiio_id is not null or easiio_id<>'')";
        $data = Yii::app()->db->createCommand($sql)->queryAll();
        $useridlist = '';
        foreach ($data as $user) {
            if (!empty($user['easiio_id']))
                $useridlist = $useridlist . $user['easiio_id'] . ';';
        }
        //设置redis缓存
        EasiioRedis::set("user_easiio_lists_update_time_" . $org_id, time(), 10);
        EasiioRedis::set("user_easiio_lists_" . $org_id, $useridlist, 10);
        return $useridlist;
    }

    //处理用户登录的信息，然后整合成字符串传递出去

    public static function processUserStatus($phoneStatus) {
        $endpointArray = array();
        if (isset($phoneStatus)) {
            foreach ($phoneStatus as $phone) {
                $online = $phone->online;
                if ($online == false && count($phone->usrlocs) > 1)
                    $online = true;
                //只有在线的时候，才返回显示数据
                if ($online) {
                    $endpointArray[] = array("easiio_id" => $phone->easiio_id, "status" => self::userStatus($phone->usrlocs));
                }
            }
        }
        return $endpointArray;
    }

    //处理用户登录信息，然后处理成数组传递出去
    public static function processUserStatusForWeb($phoneStatus) {
        $endpointArray = array();
        if (isset($phoneStatus)) {
            foreach ($phoneStatus as $phone) {
                $online = $phone->online;
                if ($online == false && count($phone->usrlocs) > 1)
                    $online = true;
                //只有在线的时候，才返回显示数据
                if ($online) {
                    $endpointArray[$phone->easiio_id] = array("device" => self::userStatusForWeb($phone->usrlocs));
                }
            }
        }
        return json_encode($endpointArray);
    }

    public static function userStatus($usrlocs) {
        $count = 0;
        $flag_mobile = false;
        $flag_phone = false;
        foreach ($usrlocs as $userloc) {
            $useragent = strtolower($userloc->{'user-agent'});
            if (strpos($useragent, 'mobile') !== false || strpos($useragent, 'ios') !== false || strpos($useragent, 'android') !== false || strpos($useragent, 'asipbx') !== false || $useragent == "n/a") {
                $flag_mobile = true;
            } else {
                $flag_phone = TRUE;
            }
        }
        if ($flag_mobile) {
            $count = $count + 1;
        }
        if ($flag_phone) {
            $count = $count + 2;
        }
        return $count;
    }

    public static function userStatusForWeb($usrlocs) {
        $array = array(
            "count" => null,
            "mobile" => null,
            "hardphone" => null,
        );
        $count = 0;
        $flag_mobile = false;
        $flag_phone = false;
        foreach ($usrlocs as $userloc) {
            $useragent = strtolower($userloc->{'user-agent'});
            if (strpos($useragent, 'mobile') !== false || strpos($useragent, 'ios') !== false || strpos($useragent, 'android') !== false || strpos($useragent, 'asipbx') !== false || $useragent == "n/a") {
                $array['mobile'] = $useragent;
                if ($useragent == "n/a") {
                    $array['mobile'] = Yii::t("default", "Unknow Device");
                }
                $flag_mobile = true;
            } else {
                $flag_phone = TRUE;
                $array['hardphone'] = $useragent;
            }
        }
        if ($flag_mobile) {
            $count = $count + 1;
        }
        if ($flag_phone) {
            $count = $count + 2;
        }
        $array['count'] = $count;
        return $array;
    }

    public static function searchDomainUser($easiio_id, $numbers) {
        $temp_numbers = explode(",", $numbers);
        $temp_numbers2 = array();
        foreach ($temp_numbers as $key => $value) {
            if (empty($value)) {
                unset($temp_numbers[$key]);
            }
            $temp_numbers2[] = "'" . $value . "'";
        }

        //    6503333333,7885397763,6502233665,16508300751,55558885555,66555666666,18606004265,6507633778,18606004265,17606460283,15980822536,16502413732,6502654228,18667910001,13799976042,15959903635,18657506123,13970976355,13860441281,18960939748,059185611636,18722893473,18707002421,15980535643,13790138820,15980500620,15822346150,15185504131,4001006688,13799349632,18886187837,13685023123,18603023552,13559163132,13599448595,13860176381,13101419503,15822864354,15922168192,15106091679,18650005133,15822777212,13612079308,15959067476,15005027460,18705078079,280781066,13799766926,13920194796,15985718429,79095837898,15085391188,13625064767,16502763706,15822716122,13827390805,13960801446,13821279561,13642191349,295325608,15880305987,15093273659,13489995786,18960607028,15980105103,15222790265,15960083720,15822408373,13459176986,15060406270,13860119453,18643431566,18559208258,18559208258,18559208258,059185961288,13821280402,13963879961,15922004600,13859904490,13799848162,15859146167,15160064960,18622061003,18622305141,15922126120,13063056549,18210320103,15160089794,15980537394,18919875757,13802053486,13763881048,15900260153,13178355178,15922069551,15122526185,18506029636,15980967889,15122096686,15959020543,13685048587,15900208526,18802271370,13616001031,15398853454,13806048007,15880065334,13959171450,13752254546,15980508660,823067062,15122743032,15011533263,15620980380,15620980380,15112414633,13625073508,18205912057,18920073978,13516287317,18500781778,15980268683,15960270220,13599523675,15980553327,18350267547,18750105300,13960975373,13656030832,18681809935,18900269315,13622063722,18249167925,15556988958,18050052183,15980637776,15959086502,18622020791,15822230715,15822437068,13928935913,15822864575,18359703383,13437133821,18205927836,13110779126,18750114710,15806019245,13599951675,15822439167,13696809184,13512916564,15902272536,15980839795,15822864346,13512430981,18701427157,13859967357,18650810051,18850468239,18650081204,13920460217,13810419616,15822167033,18559932327,15859034705,102,13616029973,15222079116,15959295248,13323838882,13577179309,18083855997,18210236271,13506995897,18950278956,18210022450,13030891280,15999581568,13774675720,18875990698,15804921301,13802057597,13646025044,13502067364,13512854489,13802033901,15980810037,13682033417,15980967889,16505392429,13599527706,15359003807,13178031090,13516220815,13612061786,13652199673,14085331267,13194099867,13600878268,18650805625,15606064860,18559970779,13205002431,16507633777,13400608210,05925379191,18885287464,16503760513,13860451056,16502044489,13426225487,15593390005,13646012247,13779988849,18060717258,16506463960,05925896333,13981837581,05922179176,13560058758,18662186175,18884233561,15005028363,1234,16507633111,222222222,5722,5787,6507633123,15922176881,15859035176,18659210261,18650194103,18613220588,13655062273,6507633456,7885397849,1,10,11,12,13,14,15,16,17,18,19,2,3,4,5,6,6507638888,7,8,9,1845464545446,13978826097,18659225668,13533939414,18120826528,18959213481,13950116002,6504253931,15750738936,13400784839,18250857077,15280249572,18606007761,7885397761,15606953216,6507633125,15345936929,18685661965,04407403450917,07403450917,180606007764,7885397764,13134969168,13515929896,18750001986,18502211653,7885397777,12345678900,123456885558888,18606007768,7885397768,18913026185,13599058987,18606007770,7885397770,7885397783,18606007765,7885397765,10086,7885397779,18606007762,7885397762,7885367765,7885397776,18606007766,7885397766,18606007767,7885397767,18606007769,7885397769,18606004211,6508563256,8885263526,8885287565,18606007760,7885397760,13665089964,18615727888,076989015769,13686695765,6507633770,6507633771,18906025968,18812345678,15260201639,18659297629,13774697701,15170047889,15880180697,13400669442,18965366078,7885390001,15880202130,18033989155,15805928506,8005688379,18750752366,18616779753,13950128298,18628165988,13850048552,
        //        $numbers = implode(",", $temp_numbers);
        $numbers = implode(",", $temp_numbers2);
        //        echo $numbers;
        $data = self::model()->findAll("username in ($numbers)");
        //        EasiioAUtils::aPrint($data);
        //        $data = self::model()->findAll("org_id=" . $org_id . " and username in (" . $numbers . ")");
        //        存放最后返回的数组
        $return = array();
        if (!empty($data)) {
            foreach ($data as $key => $value) {
                $return[$key]["number"] = $value->username;
                if (!(strtolower(pinyin::pinyinTo($value->firstname)) == strtolower($value->firstname))) {
                    $temp = $value->firstname;
                    $value->firstname = $value->lastname;
                    $value->lastname = $temp;
                }
                $return[$key]["firstname"] = !empty($value->firstname) ? $value->firstname : "";
                $return[$key]["lastname"] = !empty($value->lastname) ? $value->lastname : "";
                $return[$key]["easiio_id"] = $value->easiio_id;
                $return[$key]["head_image"] = Yii::app()->params['splashUrl'] . $value->head_image;
            }

            return $return;
        } else {
            return "";
        }
    }

    //    public static function searchDomainUserOld($easiio_id, $numbers) {
    //        $temp_numbers = explode(",", $numbers);
    //        $data = self::model()->findAll("username in (" . $numbers . ")");
    ////        $data = self::model()->findAll("org_id=" . $org_id . " and username in (" . $numbers . ")");
    ////        存放最后返回的数组
    //        $return = array();
    ////        存放key
    //        $temp = array();
    ////        存放没查到的号码的数据
    //        $return1 = array();
    //        if (!empty($data)) {
    //            foreach ($data as $value) {
    //                $return[$value->username]["firstname"] = $value->firstname;
    //                $return[$value->username]["lastname"] = $value->lastname;
    //                $return[$value->username]["easiio_id"] = $value->easiio_id;
    //                $temp[] = $value->username;
    //            }
    //
		//            foreach ($temp_numbers as $value) {
    //                if (!in_array($value, $temp)) {
    //                    $return1[$value] = "no";
    //                }
    //            }
    //            return CMap::mergeArray($return, $return1);
    //        } else {
    //            return "";
    //        }
    //    }

    public function setEasiioPhoneByPhone($phone) {
        if (empty($phone)) {
            return FALSE;
        }
        $phone = NormalFunctions::phoneNumberToStandardByEnv($phone);

        //操作三张表，将pstn_number表中的数据更新，phone_number表中的数据更新，user表的数据同时同时更新
        //设置phoneNumber
        $phoneNumberModel = PhoneNumber::model()->find("number=" . "'$phone'");
        //var_dump($phoneNumberModel);
        if (empty($phoneNumberModel)) {
            return FALSE;
        }
        $phoneNumberModel->used = 1;
        $phoneNumberModel->user_id = $this->id;
        if (!$phoneNumberModel->save()) {
            return false;
        }

        //设置pstnNumber表中数据
        $tempArray = NormalFunctions::phoneNumberToCountryCodeAndSimplePhone($phone);
        $country_code = $tempArray['country_code'];
        $phone_number = $tempArray['phone_number'];
        $pstnNumberModel = PstnNumber::model()->find("phone_number=" . "'$phone_number'" . " and country_code=" . "'$country_code'");
        if (empty($pstnNumberModel)) {
            $pstnNumberModel = new PstnNumber();
            $pstnNumberModel->phone_number = $phone_number;
        }
        $pstnNumberModel->status = "assigned";
        $pstnNumberModel->assign_obj = "user";
        $pstnNumberModel->assign_app = "easiio_pbx";
        $pstnNumberModel->assign_oid = $this->id;
        $pstnNumberModel->assign_time = date("Y-m-d H:i:s");
        if (!$pstnNumberModel->save()) {
            return FALSE;
        } else {
            // var_dump($pstnNumberModel);
        }
        $this->easiio_phone = $phone;
        if ($this->save()) {
            return true;
        } else {
            var_dump($this->errors);
        }
    }

    public static function addUserByParams($username, $firstname, $lastname, $password, $status = 2, $ext = null, $org_id = null) {

        $org_id = !empty($org_id) ? $org_id : Yii::app()->user->org_id;
        $userModel = new User();
        $userModel->username = $username;
        $userModel->status = $status;
        $userModel->firstname = $firstname;
        $userModel->lastname = $lastname;
        $userModel->password = $password;
        $userModel->password_repeat = $password;
        $userModel->org_id = $org_id;
        if (!empty($ext)) {
            $userModel->ext = $ext;
            ;
        }
        if (!$userModel->save()) {
            return false;
            //var_dump($userModel->errors);
        }
        $userModel->updateEasiioIdAndSipInfo();
        return $userModel;
    }

    //创建用户，传递用户名，密码，详细信息数组
    //例如 array('firstname'=>'eric','lastname'=>'wang')
    public static function addUser($username, $password, $array = array()) {
        $userModel = new User();
        $userModel->username = $username;
        $userModel->password = $password;
        $userModel->attributes = $array;
        if (!$userModel->save()) {
            return false;
            echo json_encode($userModel->errors);
        }
        $userModel->updateEasiioIdAndSipInfo();
        return $userModel;
    }

    public function extHasExits($ext, $org_id) {
        $model = self::model()->find("ext=$ext and org_id=$org_id");
        if (!empty($model)) {
            return true;
        } else {
            false;
        }
    }

    public static function getUserGroupId($org_id, $user_id) {
        $user_group = UserGroup::model()->find("org_id=$org_id and user_id=$user_id");
        if (!empty($user_group)) {
            $modelGroup = Group::model()->findByPk($user_group->group_id);
            if (empty($modelGroup)) {
                return -1;
            }
            return $user_group->group_id;
        } else {
            return -1;
        }
    }

    public static function getUserGroupWeight($org_id, $user_id) {
        $user_group = UserGroup::model()->find("org_id=$org_id and user_id=$user_id");
        if (!empty($user_group)) {
            $modelGroup = Group::model()->findByPk($user_group->group_id);
            if (empty($modelGroup)) {
                return 100;
            }
            return $user_group->weight;
        } else {
            return 100;
        }
    }

    public static function getEasiioIDByUserID($user_id) {
        $model = User::model()->findByAttributes(array('id' => $user_id));
        return !empty($model->easiio_id) ? $model->easiio_id : null;
    }

    public function checkExt($attribute, $params) {
        if (!$this->compareOrgExtLimitWithUsers($this->org_id)) {
            $this->addError($attribute, Yii::t("default", "The number of users has exceeded the limit，Please contact the administrator."));
        }
        if (!NormalFunctions::checkExt($this->$attribute)) {
            $this->addError($attribute, Yii::t("default", "The extension does not conform to the rules"));
        }
        if ($this->isNewRecord) {
            if (in_array($this->$attribute, $this->getOrgExtList($this->org_id))) {
                $this->addError($attribute, Yii::t("default", "The extension number is already in use"));
            }
        } else {
            if (in_array($this->$attribute, $this->getOrgExtList($this->org_id, $this->id))) {
                $this->addError($attribute, Yii::t("default", "The extension number is already in use"));
            }
        }
    }

    public function compareOrgExtLimitWithUsers($org_id) {

        $organization = Organization::model()->findByPk($org_id);
        $sql = "select count(*) as number from user where org_id=$org_id";
        $result = Yii::app()->db->createCommand($sql)->queryAll();
        $numbers = intval($result[0]['number']);
        if (intval($organization->ext_limit) >= $numbers) {
            return true;
        } else
            return false;
    }

    //检测当前分机号是否在org里面
    //如果该用户是后添加的，就不现实该用户的分机号
    public static function getOrgExtList($org_id, $filterUserId = null) {
        //$org_id=  !empty($org_id)?$org_id:Yii::app()->user->org_id;
        $sql = "select ext from user where org_id=$org_id";
        $result = Yii::app()->db->createCommand($sql)->queryAll();
        $array = CHtml::listData($result, "ext", "ext");
        if (!empty($filterUserId)) {
            $model = self::model()->findByPk($filterUserId);
            if (!empty($model)) {
                unset($array[$model->ext]);
            }
        }
        return $array;
    }

    //当用户保存成功以后，获取用户easiio_id和sip_info的注册信息
    public function updateEasiioIdAndSipInfo() {
        $this->scenario = "update";
        //容错处理，取不到easiio_id出错的容错性
       
        for($i=0;$i<3;$i++){
            $responseJson = EasiioBaseAPI::registerByUserId($this->id);
            if(isset($responseJson) && isset($responseJson->easiio_id) && $responseJson->easiio_id != ''){
                break;
            }
        }
        if (isset($responseJson) && isset($responseJson->easiio_id) && $responseJson->easiio_id != '') {
            $this->easiio_id = $responseJson->easiio_id;
            if ($this->save()) {
                $sipinfo = EasiioBaseAPI::provisioningAddForUser($this->easiio_id, $this->password);
                if (isset($sipinfo) && $sipinfo != '') {
                    $this->sip_info = $sipinfo;
                }
                $this->save();
            } else {
                var_dump($this->errors);
            }
        }
    }

    //返回json数据字符串
    public static function getStatusForWeb($org_id) {
        $time = EasiioRedis::get("user_status_for_web_update_time_" . $org_id, 10);
        if (!empty($time)) {

            if ((intval(time()) - intval($time)) < 60) {
                $data = EasiioRedis::get("user_status_for_web_data_" . $org_id, 10);
                if (!empty($data)) {
                    return $data;
                }
            }
        }
        $userlist = self::getOrgUserEasiioIdList($org_id);
        $phoneStatus = EasiioBaseAPI::checkPhoneStatus($userlist);
        $data = User::processUserStatusForWeb($phoneStatus);

        //设置redis缓存
        EasiioRedis::set("user_status_for_web_update_time_" . $org_id, time(), 10);
        EasiioRedis::set("user_status_for_web_data_" . $org_id, $data, 10);
        return $data;
    }

    public static function SuperAmdinLevel() {
        return array(
            self::SUPER_ADMIN_LEVEL_FIRST => Yii::t("default", "First Super Admin"),
            self::SUPER_ADMIN_LEVEL_SECOND => Yii::t("default", "Second Super Admin"),
            self::SUPER_ADMIN_LEVEL_TTHIRD => Yii::t("default", "Third Super Admin"),
        );
    }

    public static function getSuperAdminLevelByLevel($super_admin_level) {
        $array = self::SuperAmdinLevel();
        foreach ($array as $key => $value) {
            if ($key <= $super_admin_level) {
                unset($array[$key]);
            }
        }
        //$array[0]=Yii::t("default","Not Super Admin");
        return $array;
    }

    public static function getUserModelByEasiioId($easiio_id) {
        $model = self::model()->find('easiio_id=' . $easiio_id);

        return $model;
    }

    public static function getUserModelByPhoneNumber($phone) {
        $model = self::model()->find("username='$phone'");
        //        $model = self::model()->find("mobile='$phone' or username='$phone'");
        //        $model = self::model()->find("phone='$phone' or username='$phone'");
        return $model;
    }

    public static function getImsShareStatus($org_id, $easiio_id) {
        if (empty($org_id) || empty($easiio_id)) {
            return 0;
        } else {
            $model = ImsLines::model()->find("org_id=$org_id and easiio_id='$easiio_id'");
            return empty($model) ? 0 : $model->shareable;
        }
    }

    public static function getImsShareStatusId($org_id, $easiio_id) {
        $model = ImsLines::model()->find("org_id=$org_id and easiio_id='$easiio_id'");
        if (empty($model)) {
            return 0;
        } else {
            return $model->id;
        }
    }

    //    检查成员是否有IMS号码权限
    public static function checkIMSBind($org_id, $easiio_id) {
        $result = User::model()->find("org_id=$org_id and easiio_id='$easiio_id'");
        if (empty($result)) {
            return "";
        } else {
            return $result;
        }
    }

    //    检查成员是否绑定IMS号码2
    public static function checkIMSBind2($org_id, $easiio_id) {
        $result = ImsLines::model()->find("org_id=$org_id and easiio_id='$easiio_id'");
        if (empty($result)) {
            return "";
        } else {
            return $result;
        }
    }

    public static function getOfflineForwardStatus($status) {
        if ($status == 1) {
            return "open";
        } else {
            return "close";
        }
    }

    public static function getUserModelByOrgIdAndEasiioId($org_id, $easiio_id) {
        $model = self::model()->find("org_id=$org_id and easiio_id='$easiio_id'");
        return $model;
    }

    public static function getCommonOnOffStatus($status) {
        if ($status == 1) {
            return "open";
        } else {
            return "close";
        }
    }

    //,0关闭，1App开启（绑定设备后，2device开启 3App&Device开启）
    public static function getCommonOnOffStatus2($status) {
        if ($status == 1) {
            return "open DND for app";
        } else if ($status == 2) {
            return "open DND for device";
        } else if ($status == 3) {
            return "open DND for app and device";
        } else {
            return "close DND";
        }
    }

    //    检测是否绑定网关设备，星网rw40用
    public static function getDeviceBindStatus($easiio_id) {
        $model = self::model()->find("easiio_id='$easiio_id'");
        if (!empty($model)) {
            $username = $model->username;
            $check = StarnetGwBinding::model()->find("(sip1_easiio_id='$easiio_id' and sip1_username='$username') or (sip2_easiio_id='$easiio_id' and sip2_username='$username')");
            if (!empty($check)) {
                return "1";
            }
            return "0";
        }
        return "0";
    }

    //    检测是否绑定SVP3300，星网用
    public static function getSVP3300BindStatus($org_id, $user_id) {
        $model = PhoneUser::model()->find("org_id=$org_id and user_id=$user_id");
        if (!empty($model)) {
            return "1";
        }
        return "0";
    }

    //    检测视频网关的绑定情况，星网用
    public static function getVideoGatewayInfo($user_id) {
        $phone_g6801_id = PhoneHardware::getG6801PhoneID();
        $result = array();
        $model = PhoneUser::model()->findAll("user_id=$user_id and phone_id=$phone_g6801_id");
        if (!empty($model)) {
            //            有绑定视频网关
            $result['is_bind'] = "1";
            $phone_macs = array();
            foreach ($model as $key => $video_gate_way) {
                //                $result['video_gate_ways'][] = $video_gate_way->attributes;
                $result['video_gate_ways'][$key]['id'] = $video_gate_way->id;
                $result['video_gate_ways'][$key]['order_item_id'] = $video_gate_way->order_item_id;
                $result['video_gate_ways'][$key]['org_id'] = $video_gate_way->org_id;
                $result['video_gate_ways'][$key]['user_id'] = $video_gate_way->user_id;
                $result['video_gate_ways'][$key]['phone_id'] = $video_gate_way->phone_id;
                $result['video_gate_ways'][$key]['manufactorer'] = $video_gate_way->manufactorer;
                $result['video_gate_ways'][$key]['name'] = $video_gate_way->name;
                $result['video_gate_ways'][$key]['phone_mac'] = $video_gate_way->phone_mac;
                $result['video_gate_ways'][$key]['phone_status'] = EasiioAUtils::setNullToEmpty($video_gate_way->phone_status);
                $result['video_gate_ways'][$key]['order_id'] = $video_gate_way->id;
                $result['video_gate_ways'][$key]['zone'] = $video_gate_way->zone;
                $result['video_gate_ways'][$key]['gateway_user_list'] = $video_gate_way->gateway_user_list;
                $phone_macs[] = "'" . $video_gate_way->phone_mac . "'";
            }
            $phone_macs = implode(',', $phone_macs);
            $users = User::model()->findAll("lastname='g6801' and firstname in ($phone_macs)");
            foreach ($users as $user) {
                $result['users'][] = $user->username;
            }
        } else {
            //            没有绑定视频网关
            $result['is_bind'] = "0";
            $result['video_gate_ways'] = array();
            $result['users'] = array();
        }
        return $result;
    }

    //    检测DND状态，星网用
    public static function getDndStatus($easiio_id, $dnd) {
        //        $this->do_not_disturb
        if (self::getDeviceBindStatus($easiio_id) == "1") {
            //            绑定了设备
            return $dnd;
        } else {
            if ($dnd == "2") {
                return "0";
            } else if ($dnd == "3") {
                return "1";
            } else {
                return $dnd;
            }
        }
    }

    public function processUserCreate() {
        if (CustomerInfo::webEnv(true) == CommonConst::EN_STARNET) {
            $this->easiio_pstn = 1;
            $this->city_call = 1;
            $this->national_call = 1;
            $this->shareable = 1;
        }
    }

    //    检测是否绑定网关设备，星网rw40用
    public static function getRW40BindStatus($easiio_id) {
        $model = self::model()->find("easiio_id='$easiio_id'");
        if (!empty($model)) {
            $username = $model->username;
            $check = StarnetGwBinding::model()->find("(sip1_easiio_id='$easiio_id' and sip1_username='$username') or (sip2_easiio_id='$easiio_id' and sip2_username='$username')");
            if (!empty($check)) {
                return true;
            }
            return false;
        }
        return false;
    }

    public static function getCurrentConfigStatusName($status) {
        if ($status == 1) {
            return Yii::t("default", "ON");
        } else if ($status == 0) {
            return Yii::t("default", "OFF");
        }
    }

    public static function getCurrentMoxtraEnv($status) {
        if ($status == 1) {
            return Yii::t('default', 'sandbox');
        } else if ($status == 0) {
            return Yii::t('default', 'production');
        }
    }

    public static function getCurrentOperateName($status) {
        if ($status == 0) {
            return Yii::t('default', 'ON');
        } else if ($status == 1) {
            return Yii::t('default', 'OFF');
        }
    }

    public static function needConfigStatus($status) {
        if ($status == 0) {
            return 1;
        } else if ($status == 1) {
            return 0;
        }
    }

    public function checkPhone($attribute, $params) {
        $reg = '/^(\+)?[\d]+$/';
        if ($this->phone != "") {
            //            因为phone变成了非必填项，所以加这么一个判断
            if (!preg_match($reg, $this->phone)) {
                $this->addError('phone', Yii::t('default', 'Incorrect phone'));
            }
        }
    }

    public function checkMobile($attribute, $params) {
        $reg = '/^(\+)?[\d]+$/';
        if ($this->mobile != "") {
            //            因为mobile变成了非必填项，所以加这么一个判断
            if (!preg_match($reg, $this->mobile)) {
                $this->addError('mobile', Yii::t('default', 'Incorrect mobile'));
            }
        }
    }

    public function clearnRedisPhoneMap($user_id) {
        $model = self::model()->findByPk($user_id);
        if ($model) {
            if (!empty($model->username)) {
                EasiioRedis::del("$model->username", 14);
            }
            if (!empty($model->mobile)) {
                EasiioRedis::del("$model->mobile", 14);
            }
            if (!empty($model->phone)) {
                EasiioRedis::del("$model->phone", 14);
            }
        }
    }

    public function addRedisPhoneMap() {
        if (!empty($this->username)) {
            EasiioRedis::set("$this->username", $this->easiio_id, 14);
        }
        if (!empty($this->mobile)) {
            EasiioRedis::set("$this->mobile", $this->easiio_id, 14);
        }
        if (!empty($this->phone)) {
            EasiioRedis::set("$this->phone", $this->easiio_id, 14);
        }
    }

    /**
     * 星网视频网关G6801绑定后需要修改的账号用户名获取
     * @param type $phone_number
     * @param type $usercount
     * @return string
     */
    public static function getNotUsedUsernameWithPhoneNumber($phone_number, $usercount = 100) {

        for ($i = 0; $i < $usercount; $i++) {
            $username = $phone_number . "$i";
            $model = User::model()->find("username='$username'");
            if (empty($model)) {
                return $username;
            }
        }
        return "failed";
    }

    public function searchByCreatedDevKey($created_dev_key) {
        return $this->searchBase("created_dev_key='$created_dev_key'");
    }

    //    根据user的easiio_id数组和条数限制返回通话记录
    public static function getUserCallRecordsByUserIds($users, $limit) {
        $user_results = array();
        $records_results = array();
        if (!empty($users)) {
            foreach ($users as $key => $user) {
                $user_results[] = "'" . $user->easiio_id . "'";
            }
        }
        //                寻找通话记录
        if (!empty($user_results)) {
            $user_results_str = "(" . implode(',', $user_results) . ")";
            //          有用户，有通话记录,去通话记录表查询数据
            //        caller_userid和called_userid
            if ($limit == 0) {
                //                返回所有数据
                $temp_data = CallLog::model()->findAll(array(
                    'order' => 'insert_time desc',
                    'condition' => "caller_userid in $user_results_str or called_userid in $user_results_str"
                ));
            } else {
                //                返回最新的$limit条
                $temp_data = CallLog::model()->findAll(array(
                    'order' => 'insert_time desc',
                    'condition' => "caller_userid in $user_results_str or called_userid in $user_results_str",
                    'limit' => $limit
                ));
            }
            if (!empty($temp_data)) {
                $records_results = EasiioAUtils::modelToArray($temp_data);
            }
        }
        //        EasiioAUtils::aPrint($records_results);
        return $records_results;
    }

    public static function createUserWithUsernames($org_id, $project_id, $usernames, $options = null) {


        $organization = Organization::model()->findByPk($org_id);
        $username_prefix = $organization->username_prefix;
        $default_password = $organization->default_password;
        $datas = array(
            "new_users" => array(),
            "create_failed_users" => array(),
            "exist_users" => array(),
            "open_failed_exist_users" => array(),
            "create_user_auth_closed" => array(),
        );

        foreach ($usernames as $key => $value) {

            $username_new = $username_prefix . "_" . $value;
            $user = User::model()->find("username='$username_new'");
            if (empty($user)) {
                if ($organization->create_user_flag == 0) {
                    $data = array(
                        "easiio_username" => $username_new,
                        "create_username" => $value,
                        "erros" => array("create user auth is closed."),
                    );
                    $datas["create_failed_users"][] = $data;


                    continue;
                }

                $newUser = new User();
                $newUser->org_id = $org_id;
                $newUser->username = $username_new;
                $newUser->password = empty($default_password) ? Organization::generateDefaultPassword() : $default_password;
                $newUser->password_repeat = $newUser->password;
                $newUser->create_username = $value;
                $newUser->firstname = $value;
                $newUser->lastname = "";
                $newUser->status = 2;
                $newUser->easiio_pstn = isset($options['easiio_pstn']) ? $options['easiio_pstn'] : 1;
                $newUser->city_call = isset($options['city_call']) ? $options['city_call'] : 1;
                $newUser->national_call = isset($options['national_call']) ? $options['national_call'] : 1;
                $newUser->international_call = isset($options['international_call']) ? $options['international_call'] : 1;
                $newUser->user_flag = isset($options['user_flag']) ? $options['user_flag'] : "";
                $newUser->shareable = 1;
                $newUser->user_conference_auth = 1;
                $newUser->org_project_id = $project_id;

                if ($newUser->save()) {
                    $newUser->updateEasiioIdAndSipInfo();
                    $data = array(
                        "easiio_username" => $newUser->username,
                        "create_username" => $newUser->create_username,
                        "easiio_id" => !empty($newUser->easiio_id) ? $newUser->easiio_id : "",
                        "user_flag" => $newUser->user_flag,
                        "is_active" => $newUser->is_active,
                    );
                    $datas["new_users"][] = $data;
                } else {
                    $data = array(
                        "easiio_username" => $newUser->username,
                        "create_username" => $newUser->create_username,
                        "erros" => $newUser->errors,
                    );
                    $datas["create_failed_users"][] = $data;
                }
            } else {

                if(empty($user->easiio_id)){
                     $user->updateEasiioIdAndSipInfo();
                }
                
                
                if ($user->is_active == 1) {
                    $data = array(
                        "easiio_username" => $user->username,
                        "create_username" => $user->create_username,
                        "easiio_id" => !empty($user->easiio_id) ? $user->easiio_id : "",
                        "user_flag" => $user->user_flag,
                        "is_active" => $user->is_active,
                    );
                    $datas["exist_users"][] = $data;
                } else {
                    $user->is_active = "1";
                    if ($user->save()) {
                        $data = array(
                            "easiio_username" => $user->username,
                            "create_username" => $user->create_username,
                            "easiio_id" => !empty($user->easiio_id) ? $user->easiio_id : "",
                            "user_flag" => $user->user_flag,
                            "is_active" => $user->is_active,
                        );
                        $datas["exist_users"][] = $data;
                    } else {


                        $data = array(
                            "easiio_username" => $user->username,
                            "create_username" => $user->create_username,
                            "easiio_id" => !empty($user->easiio_id) ? $user->easiio_id : "",
                            "user_flag" => $user->user_flag,
                            "is_active" => $user->is_active,
                            "erros" => $user->errors,
                        );
                        $datas["open_failed_exist_users"][] = $data;
                    }
                }
            }
        }


        return $datas;
    }

    public static function closeUserWithUsernames($org_id, $usernames) {


        $organization = Organization::model()->findByPk($org_id);
        $username_prefix = $organization->username_prefix;
        $datas = array("close_success_users" => array(), "close_failed_users" => array(), "not_exist_users" => array());
        foreach ($usernames as $key => $value) {

            $username_new = $username_prefix . "_" . $value;
            $user = User::model()->find("username='$username_new'");
            if (empty($user)) {
                $data = array(
                    'easiio_username' => $username_new,
                    'create_username' => $value,
                );
                $datas["not_exist_users"][] = $data;
            } else {

                if ($user->is_active == 1) {
                    $user->is_active = "0";
                    if ($user->save()) {
                        $data = array(
                            'easiio_username' => $user->username,
                            'create_username' => $user->create_username,
                            'easiio_id' => !empty($user->easiio_id) ? $user->easiio_id : "",
                            "is_active" => $user->is_active,
                        );
                        $datas['close_success_users'][] = $data;
                    } else {
                        $data = array(
                            'easiio_username' => $user->username,
                            'create_username' => $user->create_username,
                            'easiio_id' => !empty($user->easiio_id) ? $user->easiio_id : "",
                            "is_active" => 0,
                        );
                        $datas['close_failed_users'][] = $data;
                    }
                } else {
                    $data = array(
                        'easiio_username' => $user->username,
                        'create_username' => $user->create_username,
                        'easiio_id' => !empty($user->easiio_id) ? $user->easiio_id : "",
                        "is_active" => $user->is_active,
                    );
                    $datas['close_success_users'][] = $data;
                }
            }
        }


        return $datas;
    }

    //        public static function openUserWithUsernames($org_id, $usernames) {
    //
		//
		//        $organization = Organization::model()->findByPk($org_id);
    //        $username_prefix = $organization->username_prefix;
    //        $datas = array("code1" => array(), "code2" => array(), "code3" => array());
    //        foreach ($usernames as $key => $value) {
    //
		//            $username_new = $username_prefix . "_" . $value;
    //            $user = User::model()->find("username='$username_new'");
    //            if (empty($user)) {
    //                $data = array(
    //                    'code' => '3',
    //                    'username' => $username_new,
    //                    'create_username' => $value,
    //                    'message' => 'User not found',
    //                );
    //            } else {
    //                $user->is_active = 1;
    //                if ($user->save()) {
    //                    $data = array(
    //                        'code' => '1',
    //                        'username' => $user->username,
    //                        'create_username' => $user->create_username,
    //                        'easiio_id' => !empty($user->easiio_id)?$user->easiio_id:"",
    //                        "is_active"=>$user->is_active,
    //                        'message' => 'Open user successfully',
    //                    );
    //                } else {
    //                    $data = array(
    //                        'code' => '2',
    //                        'username' => $user->username,
    //                        'create_username' => $user->create_username,
    //                        'easiio_id' => !empty($user->easiio_id)?$user->easiio_id:"",
    //                        'message' => $user->errors,
    //                    );
    //                }
    //            }
    //
		//           $datas['code'.$data['code']][]=$data;
    //        }
    //
		//
		//        return $datas;
    //    }


    public static function selectUserWithUsernames($org_id, $usernames) {


        $organization = Organization::model()->findByPk($org_id);
        $username_prefix = $organization->username_prefix;
        $datas = array("exist_users" => array(), "not_exist_users" => array());
        foreach ($usernames as $key => $value) {
            $username_new = $username_prefix . "_" . $value;
            $user = User::model()->find("username='$username_new'");
            if (empty($user)) {
                $data = array(
                    'easiio_username' => $username_new,
                    'create_username' => $value,
                );
                $datas['not_exist_users'][] = $data;
            } else {
                $data = array(
                    'easiio_username' => $user->username,
                    'create_username' => $user->create_username,
                    'easiio_id' => !empty($user->easiio_id) ? $user->easiio_id : "",
                    'user_flag' => $user->user_flag,
                    "is_active" => $user->is_active,
                );
                $datas["exist_users"][] = $data;
            }
        }


        return $datas;
    }

    public function changeUserAutoCallStatus($status) {
        $array = array("close", "open");
        if (!in_array($status, $array)) {
            return false;
        }
        $flag = $this->updateByPk($this->id, array(
            "auto_call_status" => $status,
            "auto_call_status_change_time" => date("Y-m-d H:i:s"),
        ));
        return $flag;
    }

    public function getUserAutoCallStatus() {
        if ($this->auto_call_status == "close" || $this->auto_call_status != "open") {

            return "close";
        } elseif ($this->auto_call_status == "open") {
            if (time() - strtotime($this->auto_call_status_change_time) > 60 * 60 * 4) {
                return "close";
            } else {
                return "open";
            }
        }
    }

    /**
     * 
     */
    public static function accessUserUpdateField() {

        return array(
            "firstname",
            "lastname",
            "email",
            "mobile",
            "acfp_flag",
            "acfp_phone",
        );
    }

    /**
     * 
     * ACFP(auto-call-fwd-pstn)
      flag分3个bit (111)
      1st bit表示 app offline时，是否自动呼转pstn
      2nd bit表示 app online时，是否自动呼转pstn
      3rd bit表示 app online时，呼转pstn是否同震(1)，否则顺震(0)

      六种取值，默认3个bit都是 disabled(0)
      4+2+1=7: offline enabled/ online enabled&simul
      4+2+0=6: offline enabled/ online enabled&seq
      4+0+0=4: offline enabled/ online disabled
      0+2+1=3: offline disabled/ online enabled&simul
      0+2+0=2: offline disabled/ online enabled&seq
      0+0+0=0: offline disabled/ online disabled
     */
    public static function acfpFlagTypes() {

        return array(
            "7",
            "6",
            "4",
            "3",
            "2",
            "0"
        );
    }

}
